package com.linshidream.intrachat.simplenio.pipeline.context;

import com.linshidream.intrachat.simplenio.pipeline.handler.MiniChannelHandler;

/**
 * Created on 2025/8/19 19:18
 *
 * @author linshidream
 * @version 1.0.0
 * @description <p>处理器持有对象，包含 channel/pipeline/handler/handler索引 </p>
 * <p>对通道内的消息进行读写都可以叫做处理器</p>
 * <p>读通道的数据 也叫做入站处理器，收消息，包含 激活、读、关闭、异常</p>
 * <p>写数据到通道 也叫做出站处理器，发消息，包含 写</p>
 */

public class MiniHandlerContext {

    /**
     * 处理器名称
     */
    private String name;

    /**
     * 处理器本身
     */
    private final MiniChannelHandler handler;

    /**
     * 通道
     */
    private final MiniChannel channel;

    /**
     * 通道的完整责任链
     */
    private final MiniChannelPipeline pipeline;

    /**
     * 处理器索引，处理器保存在数组中，索引即处理器索在位置
     */
    private int index;

    public MiniHandlerContext(MiniChannelHandler handler, MiniChannel channel, MiniChannelPipeline pipeline, int index) {
        this.channel = channel;
        this.pipeline = pipeline;
        this.handler = handler;
        this.index = index;
    }

    public MiniHandlerContext(String name, MiniChannelHandler handler, MiniChannel channel, MiniChannelPipeline pipeline, int index) {
        this.name = name;
        this.channel = channel;
        this.pipeline = pipeline;
        this.handler = handler;
        this.index = index;
    }

    public String handlerName() {
        return name;
    }

    public MiniChannel channel() {
        return channel;
    }

    public MiniChannelHandler handler() {
        return handler;
    }


    /**
     * 激活事件，向下一个处理器传播
     */
    public void fireChannelActive() {
        pipeline.fireChannelActive(index + 1);
    }

    /**
     * 读事件，向下一个处理器传播
     *
     * @param msg
     */
    public void fireChannelRead(Object msg) {
        pipeline.fireChannelRead(msg, index + 1);
    }

    /**
     * 关闭事件，向下一个处理器传播
     */
    public void fireChannelInactive() {
        pipeline.fireChannelInactive(index + 1);
    }

    /**
     * 异常事件，向下一个处理器传播
     *
     * @param t
     */
    public void fireExceptionCaught(Throwable t) {
        pipeline.fireExceptionCaught(t, index + 1);
    }

    public void fireUserEventTriggered(Object evt) {
        pipeline.fireUserEventTriggered(evt, index + 1);
    }


    /**
     * 写事件 向前一个处理器传播
     *
     * @param msg
     */
    public void fireWrite(Object msg) {
        pipeline.fireChannelWrite(msg, index - 1);
    }

}
